<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="edit-house-content">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button type="text" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h1 class="page-title">编辑房源信息</h1>
      </div>

      <!-- 主内容区域 -->
      <el-card class="edit-form-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span>房源信息编辑</span>
            <el-tag :type="getStatusType(houseData.status)">
              {{ getStatusText(houseData.status) }}
            </el-tag>
          </div>
        </template>

        <el-form
          :model="editForm"
          :rules="formRules"
          ref="editFormRef"
          label-width="120px"
          class="edit-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="房源标题" prop="houseTitle">
                  <el-input
                    v-model="editForm.houseTitle"
                    placeholder="请输入房源标题"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="editForm.phone"
                    placeholder="请输入联系电话"
                    maxlength="11"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="房源简介" prop="houseSummary">
              <el-input
                v-model="editForm.houseSummary"
                type="textarea"
                :rows="3"
                placeholder="请输入房源简介"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="房源位置" prop="houseLocation">
              <el-input
                v-model="editForm.houseLocation"
                placeholder="请输入房源位置"
                maxlength="100"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="户型" prop="layout">
                  <el-select v-model="editForm.layout" placeholder="请选择户型">
                    <el-option label="一居室" :value="1"></el-option>
                    <el-option label="两居室" :value="2"></el-option>
                    <el-option label="三居室" :value="3"></el-option>
                    <el-option label="四居室" :value="4"></el-option>
                    <el-option label="五居室" :value="5"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="楼层" prop="floor">
                  <el-input
                    v-model="editForm.floor"
                    placeholder="如：5/10"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="朝向" prop="orientation">
                  <el-select v-model="editForm.orientation" placeholder="请选择朝向">
                    <el-option label="东" value="东"></el-option>
                    <el-option label="南" value="南"></el-option>
                    <el-option label="西" value="西"></el-option>
                    <el-option label="北" value="北"></el-option>
                    <el-option label="东南" value="东南"></el-option>
                    <el-option label="东北" value="东北"></el-option>
                    <el-option label="西南" value="西南"></el-option>
                    <el-option label="西北" value="西北"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="租金" prop="rent">
                  <el-input-number
                    v-model="editForm.rent"
                    :min="1"
                    :max="999999"
                    placeholder="请输入租金"
                    style="width: 100%"
                  />
                  <span class="unit">元/月</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="支付方式" prop="paymentType">
                  <el-select v-model="editForm.paymentType" placeholder="请选择支付方式">
                    <el-option label="月付" :value="1"></el-option>
                    <el-option label="季付" :value="2"></el-option>
                    <el-option label="年付" :value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="押金类型" prop="depositType">
                  <el-select v-model="editForm.depositType" placeholder="请选择押金类型">
                    <el-option label="押1付1" :value="1"></el-option>
                    <el-option label="押1付3" :value="2"></el-option>
                    <el-option label="年押金" :value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="地铁信息">
              <el-input
                v-model="editForm.subwayInfo"
                placeholder="请输入地铁信息"
                maxlength="100"
              />
            </el-form-item>
          </div>

          <!-- 配套设施 -->
          <div class="form-section">
            <h3 class="section-title">配套设施</h3>
            <div class="facilities-grid">
              <el-checkbox v-model="editForm.complementaryFacilities.hasFridge">冰箱</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasBed">床</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasWasher">洗衣机</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasWaterHeater">热水器</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasWifi">WiFi</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasSofa">沙发</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasKitchen">厨房</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasRangeHood">油烟机</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasGasStove">燃气灶</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasTV">电视</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasAirConditioner">空调</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasCloset">衣柜</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasSmartDoorLock">智能门锁</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasBalcony">阳台</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasCentralHeating">集中供暖</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasCupBoard">橱柜</el-checkbox>
              <el-checkbox v-model="editForm.complementaryFacilities.hasDiningTable">餐桌</el-checkbox>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="saveChanges" :loading="saving">
              保存修改
            </el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import UserLayout from '@/components/layout/UserLayout.vue'
import {
  getHouseByHouseId,
  updateHouseInfo,
  updateComplementaryFacilities
} from '@/utils/apiService'

const route = useRoute()
const router = useRouter()
const activeMenu = ref('my-houses')
const activeIndex = ref('3')

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const editFormRef = ref()
const houseData = ref({})

// 编辑表单数据
const editForm = ref({
  userId: null,
  houseId: null,
  houseTitle: '',
  houseSummary: '',
  houseLocation: '',
  layout: null,
  floor: '',
  orientation: '',
  phone: '',
  rent: null,
  paymentType: null,
  depositType: null,
  subwayInfo: '',
  complementaryFacilities: {
    complementaryFacilityId: null,
    hasFridge: false,
    hasBed: false,
    hasWasher: false,
    hasWaterHeater: false,
    hasWifi: false,
    hasSofa: false,
    hasKitchen: false,
    hasRangeHood: false,
    hasGasStove: false,
    hasTV: false,
    hasAirConditioner: false,
    hasCloset: false,
    hasSmartDoorLock: false,
    hasBalcony: false,
    hasCentralHeating: false,
    hasCupBoard: false,
    hasDiningTable: false
  }
})

// 表单验证规则（编辑模式：去掉必填验证，保留格式验证）
const formRules = {
  // 房源标题：不要求必填
  houseTitle: [],

  // 房源简介：不要求必填
  houseSummary: [],

  // 房源位置：不要求必填
  houseLocation: [],

  // 户型：不要求必填
  layout: [],

  // 楼层：保留格式验证，但不要求必填
  floor: [
    { pattern: /^\d+\/\d+$/, message: '楼层格式错误，应为：所在楼层/总楼层', trigger: 'blur' }
  ],

  // 朝向：不要求必填
  orientation: [],

  // 联系电话：保留格式验证，但不要求必填
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误', trigger: 'blur' }
  ],

  // 租金：保留最小值验证，但不要求必填
  rent: [
    { type: 'number', min: 1, message: '租金必须大于0', trigger: 'blur' }
  ],

  // 支付方式：不要求必填
  paymentType: [],

  // 押金类型：不要求必填
  depositType: []
}

// 获取房源详情
const fetchHouseDetail = async () => {
  const houseId = route.params.id
  if (!houseId) {
    ElMessage.error('房源ID不存在')
    goBack()
    return
  }

  loading.value = true
  try {
    console.log('正在获取房源详情，houseId:', houseId, '类型:', typeof houseId)
    const response = await getHouseByHouseId(houseId)
    console.log('后端响应:', response)

    if (response.data.code === '200' || response.data.code === 200) {
      houseData.value = response.data.data

      // 填充表单数据
      // 获取用户ID（使用与LandlordView相同的逻辑）
      let userId = localStorage.getItem('userId')
      if (!userId) {
        const userInfo = localStorage.getItem('userInfo')
        if (userInfo) {
          try {
            const parsedUserInfo = JSON.parse(userInfo)
            userId = parsedUserInfo.id
          } catch (e) {
            console.error('解析userInfo失败:', e)
          }
        }
      }
      userId = userId || 1 // 如果还是没有，使用默认值1
      console.log('编辑页面使用的用户ID:', userId)

      editForm.value = {
        userId: parseInt(userId),
        houseId: houseData.value.houseId,
        houseTitle: houseData.value.houseTitle || '',
        houseSummary: houseData.value.houseSummary || '',
        houseLocation: houseData.value.houseLocation || '',
        layout: houseData.value.layout,
        floor: houseData.value.floor || '',
        orientation: houseData.value.orientation || '',
        phone: houseData.value.phone || '',
        rent: houseData.value.rent,
        paymentType: houseData.value.paymentType,
        depositType: houseData.value.depositType,
        subwayInfo: houseData.value.subwayInfo || '',
        complementaryFacilities: {
          complementaryFacilityId: houseData.value.complementaryFacilities?.complementaryFacilityId || null,
          hasFridge: houseData.value.complementaryFacilities?.hasFridge || false,
          hasBed: houseData.value.complementaryFacilities?.hasBed || false,
          hasWasher: houseData.value.complementaryFacilities?.hasWasher || false,
          hasWaterHeater: houseData.value.complementaryFacilities?.hasWaterHeater || false,
          hasWifi: houseData.value.complementaryFacilities?.hasWifi || false,
          hasSofa: houseData.value.complementaryFacilities?.hasSofa || false,
          hasKitchen: houseData.value.complementaryFacilities?.hasKitchen || false,
          hasRangeHood: houseData.value.complementaryFacilities?.hasRangeHood || false,
          hasGasStove: houseData.value.complementaryFacilities?.hasGasStove || false,
          hasTV: houseData.value.complementaryFacilities?.hasTV || false,
          hasAirConditioner: houseData.value.complementaryFacilities?.hasAirConditioner || false,
          hasCloset: houseData.value.complementaryFacilities?.hasCloset || false,
          hasSmartDoorLock: houseData.value.complementaryFacilities?.hasSmartDoorLock || false,
          hasBalcony: houseData.value.complementaryFacilities?.hasBalcony || false,
          hasCentralHeating: houseData.value.complementaryFacilities?.hasCentralHeating || false,
          hasCupBoard: houseData.value.complementaryFacilities?.hasCupBoard || false,
          hasDiningTable: houseData.value.complementaryFacilities?.hasDiningTable || false
        }
      }

      console.log('房源数据加载完成:', houseData.value)
      console.log('表单数据:', editForm.value)

    } else {
      ElMessage.error(response.data.message || '获取房源详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取房源详情失败:', error)
    ElMessage.error('获取房源详情失败，请重试')
    goBack()
  } finally {
    loading.value = false
  }
}

// 保存修改
const saveChanges = async () => {
  // 检查userId（如果无效，尝试重新获取）
  if (!editForm.value.userId || isNaN(editForm.value.userId)) {
    let userId = localStorage.getItem('userId')
    if (!userId) {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        try {
          const parsedUserInfo = JSON.parse(userInfo)
          userId = parsedUserInfo.id
        } catch (e) {
          console.error('解析userInfo失败:', e)
        }
      }
    }
    userId = userId || 1 // 使用默认值1
    editForm.value.userId = parseInt(userId)
    console.log('保存时重新获取的用户ID:', editForm.value.userId)
  }

  // 表单验证
  const valid = await editFormRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }

  // 确认保存
  try {
    await ElMessageBox.confirm('确定要保存修改吗？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return
  }

  saving.value = true
  try {
    // 准备房源基本信息更新数据
    const houseInfoUpdateRequest = {
      userId: editForm.value.userId,
      houseId: editForm.value.houseId,
      houseTitle: editForm.value.houseTitle,
      houseSummary: editForm.value.houseSummary,
      houseLocation: editForm.value.houseLocation,
      layout: editForm.value.layout,
      floor: editForm.value.floor,
      orientation: editForm.value.orientation,
      phone: editForm.value.phone,
      rent: editForm.value.rent,
      paymentType: editForm.value.paymentType,
      depositType: editForm.value.depositType,
      subwayInfo: editForm.value.subwayInfo
    }

    console.log('localStorage userId:', localStorage.getItem('userId'))
    console.log('editForm userId:', editForm.value.userId)
    console.log('保存房源基本信息:', houseInfoUpdateRequest)
    console.log('保存配套设施信息:', editForm.value.complementaryFacilities)

    // 详细检查每个字段
    console.log('=== 房源基本信息字段详情 ===')
    Object.keys(houseInfoUpdateRequest).forEach(key => {
      const value = houseInfoUpdateRequest[key]
      console.log(`${key}: ${value} (类型: ${typeof value})`)
    })

    // 更新房源基本信息
    console.log('正在调用 updateHouseInfo API...')
    const houseInfoResponse = await updateHouseInfo(houseInfoUpdateRequest)
    console.log('updateHouseInfo 响应:', houseInfoResponse)
    console.log('updateHouseInfo 响应码:', houseInfoResponse.data.code, '类型:', typeof houseInfoResponse.data.code)
    console.log('updateHouseInfo 响应消息:', houseInfoResponse.data.message)
    console.log('updateHouseInfo 响应数据:', houseInfoResponse.data.data)

    if (houseInfoResponse.data.code !== '200' && houseInfoResponse.data.code !== 200) {
      throw new Error(houseInfoResponse.data.message || '更新房源信息失败')
    }

    // 更新配套设施信息
    console.log('正在调用 updateComplementaryFacilities API...')
    const facilitiesResponse = await updateComplementaryFacilities(
      editForm.value.houseId,
      editForm.value.complementaryFacilities
    )
    console.log('updateComplementaryFacilities 响应:', facilitiesResponse)
    if (facilitiesResponse.data.code !== '200' && facilitiesResponse.data.code !== 200) {
      throw new Error(facilitiesResponse.data.message || '更新配套设施失败')
    }

    ElMessage.success('房源信息更新成功！')
    goBack()
  } catch (error) {
    console.error('保存修改失败:', error)
    ElMessage.error(error.message || '保存修改失败，请重试')
  } finally {
    saving.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'success'  // 待出租
    case 1: return 'warning'  // 租赁中
    case 2: return 'info'     // 已下架
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待出租'
    case 1: return '租赁中'
    case 2: return '已下架'
    default: return '未知状态'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHouseDetail()
})
</script>

<style scoped>
.edit-house-content {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.back-btn {
  color: #409eff;
  font-size: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.edit-form-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.edit-form {
  padding: 20px 0;
}

.form-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.facilities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.unit {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.form-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-house-content {
    padding: 0;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .facilities-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
  }

  .form-actions {
    flex-direction: column;
    align-items: center;
  }

  .form-actions .el-button {
    width: 200px;
  }
}
</style>
